<?php
namespace lib;
class Report {
	
	public static function __callstatic($a, $b) {
	    var_dump('no method task');
	    var_dump($a);
	}
	
	
	//设备登录
	public static function tcpLogin($params) {
	    var_dump('tcpLogin');
	    try {
	        var_dump($params);
	        $localRedis = new LocalRedis();
	        $localRedis->lpush('login-list', $params['deviceId']);
	        $localRedis->close();
	        
	    } catch (\Exception $e) {
	    }
	    return true;
	}
	
	
	//设备心跳
	public static function tcpGpsHeatbeat($params) {
	    var_dump('tcpGpsHeatbeat');
	    try {
	        $localRedis = new LocalRedis();
	        $localRedis->lpush('heart-list', ['deviceId' => $params['deviceId'], 'lock_status' => $params['lockStatus'], 'signal' => $params['onOff2'], 'ports' => $params['params']]);
	        $localRedis->close();
	    } catch (\Exception $e) {
	    }
	    
	    return true;
	}
	
	//充电结果通知的
	public static function chargeResult($params) {
	    var_dump('开始充电结果上报');
	    $sim = $params['deviceId'];
	    $portNo = $params['socketNo'];
	    
	    $time = time();
	    
	    $orderId = 0;
	    $deviceId = 0;
	    $orderIdKey = $sim . ':' . $portNo;
	    
	    //先从本地redis取
	    try {
	        var_dump('从本地redis获取');
	        $localRedis = new LocalRedis();
	        $orderId = $localRedis->get($orderIdKey);
	        $deviceId = $localRedis->get($sim);
	        $localRedis->close();
	    } catch (\Exception $e) {
	        
	    }
	    
	    if(empty($orderId)) { //本地没有获取到orderId，从redis库取
	        try {
	            var_dump('从远程redis获取');
	            $redis = new Redis();
	            $res = $redis->connect();
	            $orderId = $redis->get($orderIdKey);
	            $redis->close();
	        } catch (\Exception $e) {
	        }
	    }
	    
	    $mysql = new Mysql();
	    
	    /***
	     * 测试订单
	     * **/
	    if(!empty($orderId) && stripos($orderId, 't') === 0) {
	        $order = substr($orderId, 1);
	        $mysql->update('test_charge_order', "order_id = {$orderId}", ['status' => $params['servRes'] == 1 ? 1 : 3]);
	        $mysql->close();
	        return true;
	    }
	    
	    if(empty($orderId) || empty($deviceId)){ //从redis获取不到
	        if(empty($deviceId)) {
	            var_dump('从数据库获取device_id');
	            $deviceId = $mysql->value('device', "sim_iccid='$sim'", 'device_id');
	        }
	        
	        if(empty($orderId)){
	            var_dump('从数据库获取order_id');
	            $orderId = $mysql->value('device_port', "device_id= {$deviceId} and port_no = {$portNo}", 'current_order_id');
	        }
	    }
	    
	    if($params['servRes'] == 1){ //充电成功
	        var_dump('充电成功');
	        $mysql->update('charge_order', "order_id = {$orderId}", ['status' => 1, 'start_time' => $time]);
	        $mysql->update('device_port', "current_order_id = {$orderId}", ['status' => 1]);
	    }else{
	        var_dump('充电失败');
	        $rs = $mysql->update('charge_order', "order_id = {$orderId}", ['status' => 3]);
	        //请求退款
	        $request = new Request();
	        $request->post('chargeRefund', ['id' => $orderId]);
	        $request->close();
	    }
	    
	    $mysql->update('device', 'device_id = ' . $deviceId, ['heart_time' => $time]);
	    
	    $mysql->close();
	    return true;
	}
	
	//增加充电时间通知
	public static function addChargeResult($params) {
	    var_dump('增加时间充电时间');
	    $sim = $params['deviceId'];
	    $portNo = $params['socketNo'];
	    
	    $deviceId = 0;
	    $chargeOrderId = 0;
	    $chargeOrderIdKey = $sim . ':' . $portNo;
	    $orderId = 0;
	    $orderIdKey = 'extend:' . $sim . ':' . $portNo;
	    
	    try {//从本地取
	        var_dump('从本地redis取');
	        $localRedis = new LocalRedis();
	        $chargeOrderId = $localRedis->get($chargeOrderIdKey);
	        $orderId = $localRedis->get($orderIdKey);
	        $deviceId = $localRedis->get($sim);
	        $localRedis->close();
	    } catch (\Exception $e) {
	    }
	    
	    if(empty($chargeOrderId) || empty($orderId)) { //从远程取
	        try {
	            var_dump('从远程redis取');
	            $redis = new Redis();
	            $res = $redis->connect();
	            $chargeOrderId = $redis->get($chargeOrderIdKey);
	            $orderId = $redis->get($orderIdKey);
	            $redis->close();
	        } catch (\Exception $e) {
	        }
	    }
	    
	    $mysql = new Mysql();
	    
	    /***
	     * 测试订单
	     * **/
	    if(!empty($orderId) && stripos($orderId, 't') === 0) {
	        $order = substr($orderId, 1);
	        $mysql->update('extend_charge_order', "order_id = {$orderId}", ['status' => $params['servRes'] == 1 ? 1 : 2]);
	        $mysql->close();
	        return true;
	    }
	    
	    if(empty($chargeOrderId) || empty($orderId)){
	        var_dump('从数据库取');
	        if(empty($deviceId)) {
	            $deviceId = $mysql->value('device', "sim_iccid='{$sim}'" , 'device_id');
	        }
	        
	        if(empty($chargeOrderId)) {
	            $chargeOrderId = $mysql->value('device_port', "device_id= {$deviceId} and port_no = {$portNo}", 'current_order_id');
	        }
	        
	        $extendChargeOrder = $mysql->queryOne("select order_id,extend_quantity,amount from extend_charge_order where charge_order_id = {$chargeOrderId} order by order_id desc limit 1");
	        if(empty($extendChargeOrder)){
	            $mysql->close();
	            return true;
	        }
	        
	        $extendQuantity = $extendChargeOrder['extend_quantity'];
	        $extendAmount = $extendChargeOrder['amount'];
	        $orderId = $extendChargeOrder['order_id'];
	    }else{
	        $extendChargeOrder = $mysql->queryOne("select extend_quantity,amount from extend_charge_order where order_id = {$orderId} limit 1");
	        if(empty($extendChargeOrder)){
	            $mysql->close();
	            return true;
	        }
	        $extendQuantity = $extendChargeOrder['extend_quantity'];
	        $extendAmount = $extendChargeOrder['amount'];
	    }
	    
	    if($params['servRes'] == 1){ //增加充电成功
	        $mysql->update('extend_charge_order', "order_id = {$orderId}", ['status' => 1]);
	        $mysql->query("update charge_order set charge_quantity = charge_quantity + {$extendQuantity},amount = amount + {$extendAmount} where order_id={$chargeOrderId}");
	    }else{ //失败
	        $mysql->update('extend_charge_order', "order_id = {$orderId}", ['status' => 2]);
	        
	        
	        //请求退款
	        $request = new Request();
	        $request->post('extendChargeRefund', ['id' => $orderId]);
	        $request->close();
	    }
	    $mysql->update('device', "sim_iccid = '{$sim}'", ['heart_time' => time()]);
	    $mysql->close();
	    return true;
	}
	
	//停止充电结果通知
	public static function stopChargeResult($params) {
		var_dump('stopChargeResult');
		
		var_dump($params);
		
		//{"avgPower":0,"chargeTime":0,"deviceId":"89860438151830108265","errCode":0,"maxPower":0,"servRes":1,"socketNo":3,"statuscode":200,"vhargeVolume":0}
		
		if($params['servRes'] == 1) {
		    $request = new Request();
		    $data = [
		        'sim'             => $params['deviceId'],
		        'device_id'       => 0,
		        'order_id'        => 0,
		        'port_no'         => $params['socketNo'],
		        'consume_time' => isset($params['chargeTime']) ? $params['chargeTime'] : 0, //充电时间
		        'consume_energy' => isset($params['vhargeVolume']) ? $params['vhargeVolume'] : 0,//用电量
		        'avg_power' => isset($params['avgPower']) ? $params['avgPower'] : 0, //平均功率
		        'max_power' => isset($params['maxPower']) ? $params['maxPower'] : 0, //最大功率
		        'stop_reason' => -1, //停止原因
		    ];
		    
		    try {
		        $localRedis = new LocalRedis();
		        $orderId = $localRedis->get($params['deviceId'] . ':' . $params['socketNo']);
		        if(!empty($orderId)) {
		            
		            /***
		             * 测试订单
		             * **/
		            if(stripos($orderId, 't') === 0) {
		                $order = substr($orderId, 1);
		                try {
		                    $mysql = new Mysql();
		                    $mysql->update('test_charge_order', "order_id = {$orderId}", ['status' => 2]);
		                    $mysql->close();
		                } catch (\Exception $e) {
		                }
		                return true;
		            }
		            
		            
		            $data['order_id'] = $orderId;
		        }
		        
		        
		        
		        $deviceId = $localRedis->get($params['deviceId']);
		        if($deviceId) {
		            $data['device_id'] = $deviceId;
		        }
		        
		        $localRedis->close();
		        
		    } catch (\Exception $e) {
		    }
		    
		    $request->post('settlement/charge', $data);
		    $request->close();
		}
		
		
		
		return true;
	}
	
	//被动停止充电
	public static function finishChargeResult($params) {
		var_dump('finishChargeResult');
		var_dump(json_encode($params));
	
		if($params['statuscode'] == 200) {
		    $request = new Request();
		    $data = [
		        'sim'             => $params['deviceId'],
		        'device_id'       => 0,
		        'order_id'        => 0,
		        'port_no'         => $params['socketNo'],
		        'consume_time' => isset($params['chargeTime']) ? $params['chargeTime'] : 0, //充电时间
		        'consume_energy' => isset($params['vhargeVolume']) ? $params['vhargeVolume'] : 0,//用电量
		        'avg_power' => isset($params['avgPower']) ? $params['avgPower'] : 0, //平均功率
		        'max_power' => isset($params['maxPower']) ? $params['maxPower'] : 0, //最大功率
		        'stop_reason' => isset($params['eventInfo']) ? $params['eventInfo'] : 0 //停止原因
		    ];
		    
		    $orderIdKey = $params['deviceId'] . ':' . $params['socketNo'];
		    
		    if($params['chargeType'] == 2) {
		        $orderIdKey = 'online_card:' . $orderIdKey;
		    }
		    
		    try {
		        $localRedis = new LocalRedis();
		        $orderId = $localRedis->get($orderIdKey);
		        if(!empty($orderId)) {
		            
		            /***
		             * 测试订单
		             * **/
		            if(stripos($orderId, 't') === 0) {
		                $order = substr($orderId, 1);
		                try {
		                    $mysql = new Mysql();
		                    $mysql->update('test_charge_order', "order_id = {$orderId}", ['status' => 2]);
		                    $mysql->close();
		                } catch (\Exception $e) {
		                }
		                return true;
		            }
		            
		            $data['order_id'] = $orderId;
		        }
		        $deviceId = $localRedis->get($params['deviceId']);
		        if($deviceId) {
		            $data['device_id'] = $deviceId;
		        }
		        
		        $localRedis->close();
		    } catch (\Exception $e) {
		    }
		    
		    if($params['chargeType'] == 1) { //扫码的
		        var_dump(json_encode($data));
		        $rs = $request->post('settlement/charge', $data);
		    }else {
		        
		    }
		    
		    
		    $request->close();
		}
		
		
		return true;
	}
	
	
	//刷卡开始上报http://xxxx:7777/tboxmanager/updateCartUserInfo
	public static function updateCartUserInfo($params) {
		var_dump(json_encode($params));
		if($params['statuscode'] == 200) {
		    $request = new Request();
		    $data = [
		        'sim'             => isset($params['deviceId']) ? $params['deviceId'] : '',
		        'device_id'       => 0,
		        'order_id'        => 0,
		        'port_no'         => isset($params['socketNo']) ? $params['socketNo'] : 0,
		        'card_no'         => $params['cardID'],
		        'charge_type'     => isset($params['mode']) ? $params['mode'] : 0,
		        'charge_quantity' => isset($params['chargeTimeV']) ? intval($params['chargeTimeV']) : 0, //充电的时间/度数
		        
		    ];
		    
		    $cardType = isset($params['cardType']) ? intval($params['cardType']) : -1; //1：线上卡，2：线下卡
		    if(!in_array($cardType, [1, 2])) {
		        return true;
		    }
		    
		    $chargeStatus = isset($params['useStt']) ? intval($params['useStt']) : -1; //0：停止充电， 1：开始充电，2：结束充电, 查询余额
		    if(!in_array($chargeStatus, [0, 1, 2, 3])) {
		        return true;
		    }
		    
		    if($chargeStatus != 3) {
		        $localRedis = null;
		        try {
		            $localRedis = new LocalRedis();
		            
		            $deviceId = $localRedis->get($params['deviceId']);
		            if($deviceId) {
		                $data['device_id'] = $deviceId;
		            }
		        } catch (\Exception $e) {
		            
		        }
		        
		    }
		    
		    if($cardType == 1) { //线上卡
		        if($chargeStatus === 1) { //开始充电
		            $localRedis->close();
		            var_dump(json_encode($data));
		            $rs = $request->post('cardcharge/chargeOnlineCard', $data);
		            var_dump($rs);
		            $request->close();
		        }elseif($chargeStatus === 3){ //查余额
		            $rs = $request->post('cardcharge/balance', $data);
		            var_dump($rs);
		            $request->close();
		        }else {
		            $orderId = 0;
		            if(!empty($localRedis)) {
		                try {
		                    $orderId = $localRedis->get('online_card:' . $params['deviceId'] . ':' . $params['socketNo']);
		                    
		                } catch (\Exception $e) {
		                    
		                }
		                
		                $localRedis->close();
		            }
		            
		            if(!empty($orderId)) {
		                $data['order_id'] = $orderId;
		            }

		            if($chargeStatus === 2) { //增加充电
		                var_dump('增加充电');
		                $rs = $request->post('cardcharge/addChargeOnlineCard', $data);
		                $request->close();
		                var_dump($rs);
		            }elseif($chargeStatus === 0) { //停止充电
		                var_dump('停止充电');
		                $data['consume_time'] = isset($params['chargeTime']) ? $params['chargeTime'] : 0; //充电时间
		                $data['consume_energy'] = isset($params['vhargeVolume']) ? $params['vhargeVolume'] : 0;//用电量
		                $data['avg_power'] = isset($params['avgPower']) ? $params['avgPower'] : 0; //平均功率
		                $data['max_power'] = isset($params['maxPower']) ? $params['maxPower'] : 0; //最大功率
		                $data['stop_reason'] = -1; //停止原因
		                var_dump(json_encode($data));
		                $rs = $request->post('settlement/onlineCardCharge', $data);
		                $request->close();
		                var_dump($rs);
		            }
		            
		        }
		        
		    }
		    
		}
		
		return true;
	}
	
	//投币
	public static function updateTouBOrderInfo($params) {
		var_dump('updateTouBOrderInfo');
		var_dump(json_encode($params));
	
		return true;
	}
	
}









